package com.yonyou.pmclouds.discuss.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.yonyou.pmclouds.ApplicationConsts;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.basecom.exception.IllegalRequestArgException;
import com.yonyou.pmclouds.basecom.runtime.RuntimeEnvironment;
import com.yonyou.pmclouds.discuss.entity.DiscussNoticeVO;
import com.yonyou.pmclouds.discuss.entity.DiscussionListVO;
import com.yonyou.pmclouds.discuss.entity.DiscussionVO;
import com.yonyou.pmclouds.discuss.rmiitf.DiscussMaintain;
import com.yonyou.pmclouds.discuss.rmiitf.DiscussQuery;
import com.yonyou.pmclouds.outter.user.UserInfoQuery;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.yonyou.pmclouds.basecom.PMControllerConst.DEFAULT_PAGE_PAGE_START;
import static com.yonyou.pmclouds.basecom.PMControllerConst.DEFAULT_PAGE_SIZE;

@RestController
@RequestMapping("/mobile/discuss")
public class DiscussController {
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private DiscussQuery query;
    @Reference(version = ApplicationConsts.APPLICATION_VERSION)
    private DiscussMaintain maintain;
    @Autowired
    private UserInfoQuery userQuery;

    @GetMapping("/discussions")
    public DiscussionListVO queryDiscussByRelateKey(@RequestParam("key") String relateKey) throws BusinessException {
        DiscussionVO[] discussions = query.queryDiscussByRelateKey(relateKey, RuntimeEnvironment.getTenantId());
        userQuery.tranUserInfoField(discussions, new String[]{DiscussionVO.CREATOR, DiscussionVO.REPLIED_USER},
                new String[]{DiscussionVO.CREATOR_NAME, DiscussionVO.REPLIED_USER_NAME});
        // 重新构造评论的回复,后续可以考虑分两次来拿
        if (ArrayUtils.isEmpty(discussions)) {
            return new DiscussionListVO();
        }
        Map<String, List<DiscussionVO>> discussionReplyMap = new HashMap<>();
        List<DiscussionVO> comments = new ArrayList<>();
        for (DiscussionVO discussion : discussions) {
            if (StringUtils.isEmpty(discussion.getRepliedDiscuss())) {
                comments.add(discussion);
            } else {
                List<DiscussionVO> children = discussionReplyMap.get(discussion.getRepliedDiscuss());
                if (children == null) {
                    children = new ArrayList<>();
                    discussionReplyMap.put(discussion.getRepliedDiscuss(), children);
                }
                children.add(discussion);
            }
        }
        for (DiscussionVO discussion : comments) {
            List<DiscussionVO> replies = discussionReplyMap.get(discussion.getPkDiscuss());
            if (replies != null) {
                discussion.setReplies(replies.toArray(new DiscussionVO[0]));
            }
        }
        DiscussionListVO listVO = new DiscussionListVO();
        listVO.setListVO(comments.toArray(new DiscussionVO[0]));
        listVO.setTotalNum(discussions.length);
        return listVO;
    }

    @GetMapping("/notices")
    public DiscussNoticeVO[] queryNoticeByLoginUser(
            @RequestParam(name = "pageStart", required = false, defaultValue = DEFAULT_PAGE_PAGE_START) String pageStart,
            @RequestParam(name = "pageSize", required = false, defaultValue = DEFAULT_PAGE_SIZE) String pageSize) throws BusinessException {
        return query.queryNoticeByReceiver(RuntimeEnvironment.getLoginUserId(), Integer.valueOf(pageStart), Integer.valueOf(pageSize));
    }

    @GetMapping("/noticeInfo")
    public NoticeListViewWrapper queryNoticeInfoByLoginUser(
            @RequestParam(name = "pageStart", required = false, defaultValue = DEFAULT_PAGE_PAGE_START) String pageStart,
            @RequestParam(name = "pageSize", required = false, defaultValue = DEFAULT_PAGE_SIZE) String pageSize) throws BusinessException {

        DiscussNoticeVO[] notices = query.queryNoticeByReceiver(RuntimeEnvironment.getLoginUserId(), Integer.valueOf(pageStart), Integer.valueOf(pageSize));
        boolean hasUnreadNotice = query.hasUnreadNotice(RuntimeEnvironment.getLoginUserId());
        return new NoticeListViewWrapper(notices, hasUnreadNotice);
    }

    @PostMapping("/notice/read")
    public int readNotice(@RequestBody ReadMessageWrapper noticeId) throws BusinessException {
        if (noticeId == null || StringUtils.isEmpty(noticeId.getNoticeId())) {
            throw new IllegalRequestArgException();
        }
        maintain.makeNoticeRead(noticeId.getNoticeId(), RuntimeEnvironment.getLoginUserId());
        return 1;
    }

    @PostMapping("/create")
    public int makeDiscuss(@Validated @RequestBody DiscussionVO discussion, BindingResult errors) throws BusinessException {
        if (errors.hasErrors()) {
            throw new IllegalRequestArgException();
        }
        discussion.setCreator(RuntimeEnvironment.getLoginUserId());
        discussion.setCreatorName(userQuery.queryUserName(discussion.getCreator()));
        maintain.makeDiscussion(discussion);
        return 1;
    }

    @RequestMapping("/hasUnreadNotice")
    public Integer hasUnreadNotice() throws BusinessException {
        return query.countUnreadNotice(RuntimeEnvironment.getLoginUserId());
    }


    @Setter
    @Getter
    @AllArgsConstructor
    public static class NoticeListViewWrapper {
        private DiscussNoticeVO[] notices;
        private boolean hasUnread;
    }

    @Setter
    @Getter
    public static class ReadMessageWrapper {
        private String noticeId;
    }
}
